from pypcie import Device
import os

if not os.geteuid():
    pass
else:
    print("run with root！")
    exit(-2)

os.system("ls /sys/bus/pci/devices/")
PcieDeviceNumber = input("Input Bus:Dev:Fun = ")
try:
    dev = Device(PcieDeviceNumber)
    print("Vendor ID", hex(dev.vendor()))
    print("Device ID", hex(dev.device()))
    print("Revision",  hex(dev.revision()))
    print("subsystem_vendor ID", hex(dev.subsystem_vendor()))
    print("subsystem_device ID", hex(dev.subsystem_device()))
except Exception as e:
    print("Can not open device or Input error!")
    exit(-1)

bar = dev.bar
mmap = None
index = 0
isBarFound = 0
for i in bar:
    index += 1
    if i == None:
        continue
    else:
        isBarFound = 1
        print(index-1,i)
if not isBarFound:
    print("No Pcie Bar Found!")
    exit(0)
operatorBar = input("BAR index:")
offser = input("offset:")

try:
    data = dev.bar[int(operatorBar)].read((int(offser)))
    print(hex(data))
    NeedWrite = input("Need Write?(Y/y):")
    if NeedWrite == "Y" or NeedWrite == "y":
        value = hex(input("value = "))
        try:
            dev.bar[int(operatorBar)].write(int(offser),value)
            print("Write ok!")
        except Exception as e:
            print("Write Error!")
    else:
        exit(0)
except Exception as e:
    print("Read Error,Invalid offset!")
